import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from 'element-ui';
import Qs from 'qs';
import store from '@/store/index';
import router from '@/router/index';
import { getToken, getUserCode, getDataSource } from '@/utils/auth';
import { verifyUser } from '@/utils/index';

// 接口访问地址
// const BASE_URL = '/';
// const BASE_URL = '/uapws/rest/';
// const BASE_URL = 'http://192.168.1.16:8080';
// const BASE_URL = 'http://192.168.1.49:8080/approve/';
// const BASE_URL = 'http://172.16.3.101:1111/approve/';
const BASE_URL = 'http://220.178.235.60:7070/approve/';

export const service = Axios.create({
  baseURL: BASE_URL,
  timeout: 100000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  // withCredentials: true,
});

// request interceptor
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const url = config.url;
    if (url) {
      if (url.indexOf('loginByUsername') !== -1) {
        config.headers.loginType = store.getters.loginType;
        config.headers.userCode = store.getters.userCode;
      }
    }
    if (store.getters.token) {
      config.headers.uap_token = store.getters.token;
      config.headers.uap_dataSource = store.getters.dataSource;
      config.headers.uap_usercode = store.getters.userCode;
    }
    if (config.method === 'post' && typeof config.data === 'object') {
      config.data = Qs.stringify(config.data);
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  // response => {
  //   const res = response.data
  //   if (res.code !== 20000) {
  //     Message({
  //       message: res.message,
  //       type: 'error',
  //       duration: 5 * 1000
  //     })
  //     // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
  //     if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  //       MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
  //         confirmButtonText: '重新登录',
  //         cancelButtonText: '取消',
  //         type: 'warning'
  //       }).then(() => {
  //         store.dispatch('FedLogOut').then(() => {
  //           location.reload() // 为了重新实例化vue-router对象 避免bug
  //         })
  //       })
  //     }
  //     return Promise.reject('error')
  //   } else {
  //     return response.data
  //   }
  // },
  (response: any) => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 1000) {
        // Message({
        //   message: res.error_msg,
        //   type: 'error',
        //   duration: 3 * 1000,
        //   onClose: () => {
        //     // this.$router.push({ path: this.redirect || '/' });
        //     // store.dispatch('FedLogOut').then(() => {
        //     //   location.reload(); // 为了重新实例化vue-router对象 避免bug
        //     // });
        //   },
        // });
        // return false;
        store.dispatch('LoginByUsername', verifyUser()).then(() => {
          // this.$router.push({ path: this.redirect || '/' });
          // const routerName: string = router.app._route.name;
          // router.replace({
          //   path: '/redirect/documentDetails',
          // });
        });
      }
      let errorMsg: string;
      if (res) {
        errorMsg = res.error_msg;
      } else {
        errorMsg = '请求失败，请稍后重试';
      }
      Message({
        message: errorMsg,
        type: 'error',
        duration: 3 * 1000,
      });
      throw new Error('error');
    }
    return response;
  },
  (error: any) => {
    Message({
      message: `错误信息${error.message}`,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

export const post = (url: string, data?: any, config?: AxiosRequestConfig): Promise<any> => service.post(url, data, config).then((res: AxiosResponse) => {
  if (res.status === 200) {
    return Promise.resolve(res);
  }
  return Promise.reject(new Error(`访问数据失败: ${res.status}: ${res.statusText}`));
});

export const fetch = (url: string, params?: any): Promise<any> => service.get(url, { params }).then((res: AxiosResponse) => Promise.resolve(res));

export const fetchModuleData = (path: string, params?: any) => fetch(`${path}`, params).then((res: any) => {
  // console.log('server-->  res', res);
  const data = res;
  if (data.status === 200) {
    return data.data;
  }
  return Promise.reject(data.message);
});

export const postModuleData = (path: string, params?: any) => post(`${path}`, params).then((res: any) => {
  if (res.status === 200) {
    return res.data;
  }
  return Promise.reject(new Error(`访问数据失败: ${res.status}: ${res.message}`));
});

export default {
  service,
  post,
  fetch,
};
